package com.codefish.codefishseckill.security;

import com.codefish.codefishseckill.entity.AuthUser;
import com.codefish.codefishseckill.entity.User;
import com.codefish.codefishseckill.utils.CookieUtil;
import com.codefish.codefishseckill.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * jwt登录权限拦截器
 *
 * @author <a href='https://gitee.com/hzf2281'>codefish</a>
 * @version 1.0.0
 * @since 2022/08/31 上午 10:48
 */
@Component
@Slf4j
public class JwtTokenFilter extends OncePerRequestFilter {
    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //从cookie中拿到jwt token
        String jwtToken = CookieUtil.getValueByKey(request, CookieUtil.USER_INFO_KEY);
        //解析jwt token，获取用户信息
        User user = null;
        try {
            user = JwtUtils.parseJwtToken(jwtToken);
        } catch (Exception e) {
            log.debug("token:[{}]解析失败，原因：[{}]", jwtToken, e.getMessage());
        }

        if (user != null) {
            //包装成userDetails
            AuthUser authUser = new AuthUser(user);

            log.debug("用户{}认证成功，登录ip：{}，身份标识：{}", authUser.getUsername(), request.getRemoteHost(), authUser.getAuthorities().get(0));

            //将查找到的信息包装成UsernamePasswordAuthenticationToken
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                    authUser, null, authUser.getAuthorities()
            );
            //将UsernamePasswordAuthenticationToken设置到SecurityContextHolder中
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(request, response);
    }
}
